package pt.compflow.client.api;

import java.io.IOException;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;

import pt.compflow.Context;
import pt.compflow.flowontology.model.FLOWO;
import pt.compflow.flowontology.model.FlowOntologyModel;
import pt.compflow.flowontology.model.Job;
import pt.compflow.flowontology.model.Person;
import pt.compflow.storage.TripleStoreConnection;

public class JobResource extends APIBaseResource {

//	private static final Logger LOG = LoggerFactory.getLogger(PersonResource.class);
	
	@Get("json")
	public Representation get() {
		Context context = getCompFlowContext();
		TripleStoreConnection store = context.getStoreConnection();
		store.openStore();
		
		FlowOntologyModel model = store.connectModel();
		
		Person p = getPerson(model, null);
		if(p == null) {
			setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
			store.closeStore();
			return new EmptyRepresentation();
		}
				
		if(getRequestAttributes().containsKey("id")) {
			String uri = FLOWO.getURI() + getRequestAttributes().get("id");
			Job job = model.getJobWithURI(uri);
	
			if(!model.contains(p, FLOWO.owns, job)) {
				setStatus(Status.CLIENT_ERROR_NOT_FOUND);
				store.closeStore();
				return new EmptyRepresentation();
			}
					
			StringRepresentation sr = new StringRepresentation(getJobJson(model, job).toString(), MediaType.APPLICATION_JSON);
			store.closeStore();
			return sr;
		}
		
		// list
		JSONArray result = new JSONArray();
		Iterator<Job> it = p.listOwnsJobs();
		while(it.hasNext()) {
			Job job = it.next();
			result.put(getJobJson(model, job));
		}
		
		StringRepresentation sr = new StringRepresentation(result.toString(), MediaType.APPLICATION_JSON);
		
		store.closeStore();
		
		return sr;
	}
	
	@Post("json")
	public Representation create(String json) throws JSONException, IOException {
						
		JSONObject request = new JSONObject(json);
		
		if(!request.has("label") || !request.has("description") || !request.has("inputData") ||
				request.getString("label").length() <= 1 || request.getString("description").length() <= 1 || request.getString("inputData").length() <= 1) {
			setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
			return new EmptyRepresentation();
		}
		
		Context context = getCompFlowContext();
		TripleStoreConnection store = context.getStoreConnection();
		store.openStore();
		
		FlowOntologyModel model = store.connectModel();
						
		Person p = getPerson(model, null);
		if(p == null) {
			setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
			store.closeStore();
			return new EmptyRepresentation();
		}
		
		String jobTemplateId = context.getJobTemplateManager().createJobTemplate(p, request);
		Job job = context.getJobController().loadAndStartJob(p.getURI(), jobTemplateId);
		
		setStatus(Status.SUCCESS_OK);
		
		StringRepresentation sr = new StringRepresentation(job.getLocalName(), MediaType.TEXT_PLAIN);
		
		store.closeStore();
		
		return sr;
	}
		
	protected JSONObject getJobJson(FlowOntologyModel model, Job job) {
		JSONObject obj = new JSONObject();
		
		obj.put("uri", job.getURI());
		obj.put("shortUri", job.getLocalName());
		obj.put("label", job.getLabel(null));
		obj.put("description", job.getDescription(null));
							
		return obj;
	}

	
}
